package cn.edu.scau.jds.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by junbin(seraphstorm@163.com) on 2016-01-26.
 */
@MappedTypes(value = {Boolean.class, boolean.class})
@MappedJdbcTypes(value = JdbcType.TINYINT)
public class BooleanTypeHandler extends BaseTypeHandler<Boolean> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbcType) throws SQLException {
        if (parameter.equals(Boolean.TRUE)) {
            ps.setInt(i, 1);
        } else {
            ps.setInt(i, 0);
        }
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return transfer(rs.getInt(columnName));
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return transfer(rs.getInt(columnIndex));
    }

    @Override
    public Boolean getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return transfer(cs.getInt(columnIndex));
    }

    private Boolean transfer(int value) {
        if (value == 1)
            return Boolean.TRUE;
        else
            return Boolean.FALSE;
    }
}
